define(['app', 'pagination', 'datetime', 'laydate', 'autocomplete', 'filesaver','floatlayer'], function(app) {
    'use strict';
    /**
     * 退款处理前端控制器
     *
     * @author ZhangYe<banfg56@gmail.com>
     * @dete   02/23/2017
     */
    app.controller('Refund', function($scope, dataFactoryCRM, $q) {
            $scope.refundpage = { pageAll: 1, pageNow: 1, pageSize: $scope.psize, k: 125 };
            $scope.add = {};
            $scope.add_data = { userphone: '', phone: '' };
            $scope.deliveryArr = new Array(); /**邮寄信息 */
            $scope.delivery = {}; /**单条邮寄信息 */
            $scope.refundArr = new Array(); /**退款信息 */
            $scope.usercontracts = {}; /**客户流水信息 */
            $scope.pageOption = {};
            $scope.search_param = { userphone: '', sales: '', start_time: '', end_time: '', status: 0, reason: -1 };
            $scope.refundlist = [];
            $scope.export = { param: null, errMsg: '' };
            // $scope.theContract = {};
            $scope.arrPayId = new Array();
            $scope.refund_mount = 0; /**添加退款总金额 */
            $scope.isAddUser = false; /**是否展开邮寄添加界面 */
            $scope.customer = [{}];

            /**自动补全 */
            // $scope.checkCustomer = '';

            $scope.getPageOption = function() {
                var _url = 'refund/options'
                dataFactoryCRM.getDataByAPI(_url).then(function(_d) {
                    if (_d.rcode) {
                        $scope.pageOption = _d.data;
                    }
                });
            };

            /**获取客户信息 */
            $scope.getCustomer = function(newValue) {
                var _url = 'risk/getCustomers?customer=' + newValue;
                dataFactoryCRM.getDataByAPI(_url).then(function(response) {
                    if (response.rcode) {
                        $scope.customer = response.data;
                    } else {
                        $scope.customer = [{}];
                        console.log(response.msg);
                    }
                });
            };

            /**自动补全选择 */
            $scope.selectCustomer = function(selected) {
                if (selected) {
                    console.log(selected);
                    $scope.add_data.customer_id = selected.originalObject.customer_id;
                    $scope.add_data.sales_id = selected.originalObject.sales_id;
                    $scope.add_data.userphone = selected.originalObject.phone;
                    $scope.add_data.phone = selected.originalObject.phone;
                    $scope.add_data.customer_name = selected.originalObject.nickname;
                    $scope.add_data.sales_manager = selected.originalObject.sales_manager;
                    $scope.add_data.sales_subcompany = selected.originalObject.sales_sub_company;
                    /**同步退款协议用户信息 */
                    $scope.delivery.recipients = $scope.add_data.customer_name;
                    $scope.delivery.phone = $scope.add_data.phone;
                    $("#add_data_userphone1").val($scope.add_data.customer_name);
                    setTimeout(function() { $('#add_data_phone').trigger('blur') }, 50);
                    $scope.load_customer();
                }
            };

            /**获取列表页 */
            $scope.getDataList = function() {
                var listParam = $scope.search_param;
                listParam['psize'] = $scope.refundpage.pageSize;
                listParam['p'] = $scope.refundpage.pageNow;
                var _url = 'refund/index?' + $.param(listParam);
                $scope.$emit('BUSY');
                dataFactoryCRM.getDataByAPI(_url).then(function(_d) {
                    $scope.$emit('NOTBUSY');
                    if (_d.rcode) {
                        $scope.refundpage.pageSize = _d.psize;
                        $scope.refundpage.pageAll = _d.pall;
                        $scope.refundpage.pageNow = _d.p;
                        $scope.refundlist = _d.data;
                        setTimeout(function() {
                            $('.starlist').rating({ interactive: false });
                        }, 300);
                    } else {
                        $scope.refundpage.pageAll = 0;
                    }
                });
            };

            /**搜索 */
            $scope.search = function() {
                $scope.refundpage.pageNow = 1;
                $scope.getDataList();
            };
            
            /**退款记录导出 */
            $scope.export_popup = function() {

                var listParam = $scope.search_param;
                var _url = 'Refund/export_popup?' + $.param(listParam);
                dataFactoryCRM.getDataByAPIS(_url).then(function(response) {
                    var blob = new Blob([response], {
                        type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
                    });
                    saveAs(blob, '退款数据记录表' + '.xls');
                });
            };
            /**添加退款提交 */
            $scope.add_popup = function() {

                /**添加成功 */
                function addSuccess() {
                    setTimeout(function() {
                        $('.modal1').modal('show');
                        //3s后关闭
                        setTimeout(function() {
                            $('.modal1').modal('hide')
                        }, 3000)
                    }, 1000);
                }
                /**添加失败 */
                function addFail() {
                    //添加失败了,
                    setTimeout(function() {
                        $('.modal2').modal('show');
                        //3s后关闭
                        setTimeout(function() {
                            $('.modal2').modal('hide')
                        }, 3000)
                    }, 100);
                }

                function init() {
                    $scope.delivery = {};
                    $scope.deliveryArr = new Array();
                    $scope.refund = {};
                    $scope.refundArr = new Array();
                    $scope.usercontracts = {};
                    $scope.add_data = {};
                    $scope.add = {};
                    $scope.arrPayId = new Array();
                    $scope.refund_mount = '';
                    $scope.$broadcast('angucomplete-alt:clearInput');
                    $('.popup.add').form('reset');
                    setTimeout(function() { $('.ui.dropdown').dropdown() }, 50);
                }

                function add(data) {
                    $scope.$emit('BUSY');
                    $scope.busy = dataFactoryCRM.postDataByAPI('refund/add', data)
                        .then(function(d) {
                            $scope.$emit('NOTBUSY');
                            init();
                            if (d && d.rcode) {
                                addSuccess();
                                $scope.getDataList();
                            } else {
                                addFail();
                            }
                        });
                }

                function combinePay() {
                    for (var i in $scope.arrPayId) {
                        var index = $scope.arrPayId[i];
                        var post = {
                            pay_id: $scope.usercontracts[index]['pay_id'],
                            pay_mount: $scope.usercontracts[index]['pay_mount'],
                            pay_refund_mount: $scope.usercontracts[index]['refunded'],
                            refund_mount: $scope.usercontracts[index]['will_refund'],
                        }
                        $scope.refundArr.push(post);
                    }
                }

                init();

                for (var i = 0; i < $scope.pageOption.waibu.length; i++) {
                    if (31 == $scope.pageOption.waibu[i].id)
                        $scope.add_data.waibu_tousu = $scope.pageOption.waibu[i];
                }
                setTimeout(function() { $('.ui.more.dropdown').dropdown() }, 50);

                $('.ui.add').modal({
                    observeChanges: true,
                    onApprove: function() {
                        // if ($scope.isAddUser) {
                        //     alert('请先点击保存或取消按钮退出邮寄信息操作');
                        //     return false;
                        // }
                        if (!$scope.refund_mount || $scope.arrPayId.length == 0) {
                            alert('退款流水和金额不能为空');
                            return false;
                        }
                        if ($('.popup.add.form').form('is valid') && $('.popup.delivery1.form').form('is valid')) {
                            $scope.saveItem();
                            combinePay();
                            $scope.isAddUser = false;
                            $scope.delivery = {};
                            $scope.add_data.pay_mount = $scope.refund_mount;
                            $scope.add = {
                                data: $scope.add_data,
                                delivery: $scope.deliveryArr,
                                refund: $scope.refundArr,
                            };
                            console.log($scope.add_data);
                            add($scope.add);
                        } else {
                            return false;
                        }
                    }
                }).modal('show');
            };
            /**修改退款 */
            $scope.edit_popup = function(v) {

                /**更新成功 */
                function updateSuccess() {
                    setTimeout(function() {
                        $('.modal4').modal('show');
                        //3s后关闭
                        setTimeout(function() {
                            $('.modal4').modal('hide')
                        }, 3000)
                    }, 1000);
                }
                /**更新失败 */
                function updateFail() {
                    //添加失败了,
                    setTimeout(function() {
                        $('.modal5').modal('show');
                        //3s后关闭
                        setTimeout(function() {
                            $('.modal5').modal('hide')
                        }, 3000)
                    }, 1000);
                }

                function init() {
                    $scope.delivery = {};
                    $scope.deliveryArr = new Array();
                    $scope.refund = {};
                    $scope.refundArr = new Array();
                    $scope.usercontracts = {};
                    $scope.edit_data = {};
                    $scope.edit = {};
                    $scope.arrPayId = new Array();
                    $scope.refund_mount = '';
                    $scope.$broadcast('angucomplete-alt:clearInput');
                    $('.popup.add').form('reset');
                    setTimeout(function() { $('.ui.dropdown').dropdown() }, 50);
                }

                function edit(data) {
                    $scope.$emit('BUSY');
                    $scope.busy = dataFactoryCRM.postDataByAPI('refund/edit', data)
                        .then(function(d) {
                            $scope.$emit('NOTBUSY');
                            init();
                            if (d && d.rcode) {
                                $scope.msg = '退款信息更新成功';
                                updateSuccess();
                                $scope.getDataList();
                            } else {
                                $scope.msg = '退款信息更新失败';
                                updateFail();
                            }
                        });
                }
                init();
                $scope.refund_mount = this.vitem.pay_mount;
                dataFactoryCRM.getDataByAPI('refund/edit?id=' + v.refund_id).then(function(data) {
                    if (data && data.rcode) {
                        $scope.detail = data.data;
                        if (v.status == 0) {
                            $scope.delivery = data.delivery[0];
                        } else if (v.status == 30 || v.status == 31) {
                            $scope.deliveryArr = data.delivery;
                        }
                        $scope.refundArr = data.refund;
                        $scope.edit_data.customer_name = $scope.detail.customer_name;
                        $scope.edit_data.customer_phone = $scope.detail.phone;
                        $scope.edit_data.id = $scope.detail.refund_id;
                        $scope.edit_data.pay_mount = $scope.detail.pay_mount;
                        $scope.edit_data.sales_id = $scope.detail.sales_id;
                        $scope.edit_data.customer_id = $scope.detail.customer_id;
                        // $scope.edit_data.sales_id = $scope.detail.sales_id;
                        // $scope.edit_data.sales_name = $scope.detail.sales_name;
                        // $scope.edit_data.sales_manager = $scope.detail.sales_manager;
                        // $scope.edit_data.manager_name = $scope.detail.manager_name;
                        // $scope.edit_data.sales_subcompany = $scope.detail.sales_subcompany;
                        $scope.edit_data.waibu_tousu = $scope.detail.waibu_tousu;

                        var i = 0;
                        for (i = 0; i < $scope.pageOption.reasons.length; i++) {
                            if ($scope.detail.reason_id == $scope.pageOption.reasons[i].id)
                                $scope.edit_data.reason = $scope.pageOption.reasons[i];
                        }
                        for (i = 0; i < $scope.pageOption.waibu.length; i++) {
                            if ($scope.detail.waibu_tousu == $scope.pageOption.waibu[i].id)
                                $scope.edit_data.waibu_tousu = $scope.pageOption.waibu[i];
                        }
                        for (i = 0; i < $scope.pageOption.subcompany.length; i++) {
                            if ($scope.detail.sales_subcompany == $scope.pageOption.subcompany[i].sector_id)
                                $scope.edit_data.sales_company = $scope.pageOption.subcompany[i];
                        }
                        $scope.edit_data.remark = $scope.detail.remark;
                        $scope.edit_data.payee_name = $scope.detail.payee_name;
                        $scope.edit_data.payee_account = $scope.detail.payee_account;
                        $scope.edit_data.payee_way = $scope.detail.payee_way;

                        $scope.edit_data.invoice_recycle = $scope.detail.invoice_recycle;
                        $scope.edit_data.contract_recycle = $scope.detail.contract_recycle;
                        $scope.edit_data.sign_status = $scope.detail.sign_status;

                        setTimeout(function() { $('.ui.dropdown').dropdown() }, 50);

                        /**未审核编辑 */
                        if (v.status == 0) {
                            $('.ui.edit').modal({
                                observeChanges: true,
                                onApprove: function() {
                                    if ($('.popup.edit.form').form('is valid') && $('.popup.delivery2.form').form('is valid')) {
                                        $scope.saveItem();
                                        $scope.edit_data.pay_mount = $scope.refund_mount;
                                        $scope.edit = {
                                            data: $scope.edit_data,
                                            refund: $scope.refundArr,
                                            delivery: $scope.deliveryArr,
                                        };
                                        edit($scope.edit);
                                    } else {
                                        return false;
                                    }
                                }
                            }).modal('show');
                        } else if (v.status == 30) {
                            /**审核通过编辑 */
                            $('.ui.editF').modal({
                                observeChanges: true,
                                onApprove: function() {
                                    if ($scope.isAddUser) {
                                        alert('请先点击保存或者取消，结束邮寄记录操作');
                                        return false;
                                    }
                                    $scope.saveItem();
                                    $scope.edit_data.pay_mount = $scope.refund_mount;
                                    $scope.edit = {
                                        data: $scope.edit_data,
                                        refund: $scope.refundArr,
                                        delivery: $scope.deliveryArr,
                                    };
                                    edit($scope.edit);
                                }
                            }).modal('show');
                        } else if (v.status == 31) {
                            $('.ui.editC').modal({
                                observeChanges: true,
                                onApprove: function() {
                                    if ($scope.isAddUser) {
                                        alert('请先点击保存或者取消，结束邮寄记录操作');
                                        return false;
                                    }
                                    if ($('.popup.deliveryC.form').form('is valid')) {
                                        $scope.saveItem();
                                        $scope.edit_data.pay_mount = $scope.refund_mount;
                                        $scope.edit = {
                                            data: $scope.edit_data,
                                            refund: $scope.refundArr,
                                            delivery: $scope.deliveryArr,
                                        };
                                        edit($scope.edit);
                                    } else {
                                        return false;
                                    }
                                }
                            }).modal('show');
                        }
                    } else {
                        alert("获取编辑数据失败");
                    }
                });
            };
            /**退款审核 */
            $scope.confirm_popup = function(v) {

                /**更新成功 */
                function updateSuccess() {
                    setTimeout(function() {
                        $('.modal4').modal('show');
                        //3s后关闭
                        setTimeout(function() {
                            $('.modal4').modal('hide')
                        }, 3000)
                    }, 1000);
                }
                /**更新失败 */
                function updateFail() {
                    //添加失败了,
                    setTimeout(function() {
                        $('.modal5').modal('show');
                        //3s后关闭
                        setTimeout(function() {
                            $('.modal5').modal('hide')
                        }, 3000)
                    }, 1000);
                }

                function init() {
                    $scope.delivery = {};
                    $scope.deliveryArr = new Array();
                    $scope.refund = {};
                    $scope.refundArr = new Array();
                    $scope.arrPayId = new Array();
                    $scope.usercontracts = {};
                    $scope.edit_data = {};
                    $scope.edit = {};
                    $scope.refund_mount = '';
                    $scope.$broadcast('angucomplete-alt:clearInput');
                    $('.popup.add').form('reset');
                    setTimeout(function() { $('.ui.dropdown').dropdown() }, 50);
                }

                function confirm(_data, _approve) {
                    var data = { id: 0, approve: 0 };
                    data.id = _data.id;
                    data.approve = _approve;
                    // data.contract_status = _data.contract_status;
                    // data.invoice_status = _data.invoice_status;
                    // data.complain_status = _data.complain_status;
                    // data.sign_status = _data.sign_status;
                    data.remark = _data.remark;

                    $scope.busy = dataFactoryCRM.postDataByAPI('refund/confirm', data)
                        .then(function(d) {
                            init();
                            if (d && d.rcode) {
                                $scope.msg = '退款信息审核成功';
                                updateSuccess();
                                $scope.getDataList();
                                return true;
                            } else {
                                $scope.msg = '退款信息审核失败';
                                updateFail();
                                return false;
                            }
                        });
                }

                $scope.refund_mount = this.vitem.pay_mount;
                $scope.edit_data = {};
                $scope.edit = {};
                $scope.detail = {};
                $scope.deliveryArr = new Array(); /**邮寄信息 */
                $scope.refundArr = new Array(); /**退款信息 */
                dataFactoryCRM.getDataByAPI('refund/edit?id=' + v.refund_id).then(function(data) {
                    if (data && data.rcode) {
                        $scope.detail = data.data;
                        if (v.status == 31) {
                            $scope.deliveryArr = data.delivery;
                        } else {
                            $scope.delivery = data.delivery[0];
                        }
                        $scope.refundArr = data.refund;
                        $scope.edit_data.customer_name = $scope.detail.customer_name;
                        $scope.edit_data.customer_phone = $scope.detail.phone;
                        $scope.edit_data.id = $scope.detail.refund_id;
                        $scope.edit_data.pay_mount = $scope.detail.pay_mount;
                        // $scope.edit_data.sales_id = $scope.detail.sales_id;
                        // $scope.edit_data.sales_name = $scope.detail.sales_name;
                        // $scope.edit_data.sales_manager = $scope.detail.sales_manager;
                        // $scope.edit_data.manager_name = $scope.detail.manager_name;
                        // $scope.edit_data.sales_subcompany = $scope.detail.sales_subcompany;
                        $scope.edit_data.waibu_tousu = $scope.detail.waibu_tousu;

                        $scope.edit_data.invoice_recycle = $scope.detail.invoice_recycle;
                        $scope.edit_data.contract_recycle = $scope.detail.contract_recycle;
                        $scope.edit_data.sign_status = $scope.detail.sign_status;

                        var i = 0;
                        for (i = 0; i < $scope.pageOption.reasons.length; i++) {
                            if ($scope.detail.reason_id == $scope.pageOption.reasons[i].id)
                                $scope.edit_data.reason = $scope.pageOption.reasons[i];
                        }
                        for (i = 0; i < $scope.pageOption.waibu.length; i++) {
                            if ($scope.detail.waibu_tousu == $scope.pageOption.waibu[i].id)
                                $scope.edit_data.waibu_tousu = $scope.pageOption.waibu[i];
                        }
                        for (i = 0; i < $scope.pageOption.subcompany.length; i++) {
                            if ($scope.detail.sales_subcompany == $scope.pageOption.subcompany[i].sector_id)
                                $scope.edit_data.sales_company = $scope.pageOption.subcompany[i];
                        }
                        $scope.edit_data.remark = $scope.detail.remark;
                        $scope.edit_data.payee_name = $scope.detail.payee_name;
                        $scope.edit_data.payee_account = $scope.detail.payee_account;
                        $scope.edit_data.payee_way = $scope.detail.payee_way;

                        setTimeout(function() { $('.ui.more.dropdown').dropdown() }, 50);
                        if (v.status == 31) {
                            $('.ui.confirmC').modal({
                                observeChanges: true,
                                onApprove: function() {
                                    confirm($scope.edit_data, 1);
                                },
                                onDeny: function() {
                                    confirm($scope.edit_data, 0);
                                }
                            }).modal('show');
                        } else {
                            $('.ui.confirm').modal({
                                observeChanges: true,
                                onApprove: function() {
                                    confirm($scope.edit_data, 1);
                                },
                                onDeny: function() {
                                    confirm($scope.edit_data, 0);
                                }
                            }).modal('show');
                        }
                    } else {
                        alert("获取编辑数据失败");
                    }
                });
            };
            /**退款取消 */
            $scope.cancle_popup = function(v) {

                var data = { id: 0, approve: 2 };
                data.id = v.refund_id;

                $scope.busy = dataFactoryCRM.postDataByAPI('refund/confirm', data)
                    .then(function(d) {
                        if (d && d.rcode) {
                            $scope.getDataList();
                            return true;
                        } else {
                            return false;
                        }
                    });

            };
            /**删除退款 */
            $scope.remove_popup = function(v) {
                function remove(data) {
                    $scope.$emit('BUSY');
                    $scope.busy = dataFactoryCRM.postDataByAPI('refund/delete', data)
                        .then(function(d) {
                            if (d && d.rcode) {
                                $scope.delete_data = {};
                                $scope.getDataList();
                                return true;
                            } else {
                                $scope.$emit("NOTBUSY");
                                alert("删除数据失败");
                                return false;
                            }
                        });
                }
                $scope.delete_data = v;
                $('.ui .modal3').modal({
                    observeChanges: true,
                    onApprove: function() {
                        var rdata = { 'id': $scope.delete_data.refund_id };
                        remove(rdata);
                    }
                }).modal('show');
            };
            /**查看退款 */
            $scope.view_popup = function(v) {
                $scope.detail = new Array();
                $scope.refund_mount = this.vitem.pay_mount;
                $scope.edit_data = {};
                $scope.deliveryArr = new Array(); /**邮寄信息 */
                $scope.refundArr = new Array(); /**退款信息 */
                dataFactoryCRM.getDataByAPI('refund/edit?id=' + v.refund_id).then(function(data) {
                    if (data && data.rcode) {
                        $scope.detail = data.data;
                        $scope.deliveryArr = data.delivery;
                        $scope.refundArr = data.refund;
                        $scope.edit_data.customer_name = $scope.detail.customer_name;
                        $scope.edit_data.customer_phone = $scope.detail.phone;
                        $scope.edit_data.id = $scope.detail.refund_id;
                        $scope.edit_data.pay_mount = $scope.detail.pay_mount;
                        // $scope.edit_data.sales_id = $scope.detail.sales_id;
                        // $scope.edit_data.sales_name = $scope.detail.sales_name;
                        // $scope.edit_data.sales_manager = $scope.detail.sales_manager;
                        // $scope.edit_data.manager_name = $scope.detail.manager_name;
                        // $scope.edit_data.sales_subcompany = $scope.detail.sales_subcompany;
                        $scope.edit_data.waibu_tousu = $scope.detail.waibu_tousu;

                        $scope.edit_data.invoice_recycle = $scope.detail.invoice_recycle;
                        $scope.edit_data.contract_recycle = $scope.detail.contract_recycle;
                        $scope.edit_data.sign_status = $scope.detail.sign_status;

                        var i = 0;
                        for (i = 0; i < $scope.pageOption.reasons.length; i++) {
                            if ($scope.detail.reason_id == $scope.pageOption.reasons[i].id)
                                $scope.edit_data.reason = $scope.pageOption.reasons[i];
                        }
                        for (i = 0; i < $scope.pageOption.waibu.length; i++) {
                            if ($scope.detail.waibu_tousu == $scope.pageOption.waibu[i].id)
                                $scope.edit_data.waibu_tousu = $scope.pageOption.waibu[i];
                        }
                        for (i = 0; i < $scope.pageOption.subcompany.length; i++) {
                            if ($scope.detail.sales_subcompany == $scope.pageOption.subcompany[i].sector_id)
                                $scope.edit_data.sales_company = $scope.pageOption.subcompany[i];
                        }
                        $scope.edit_data.remark = $scope.detail.remark;
                        $scope.edit_data.payee_name = $scope.detail.payee_name;
                        $scope.edit_data.payee_account = $scope.detail.payee_account;
                        $scope.edit_data.payee_way = $scope.detail.payee_way;

                        setTimeout(function() { $('.ui.more.dropdown').dropdown() }, 50);

                        $('.ui.view').modal({
                            observeChanges: true,
                        }).modal('show');
                    } else {
                        alert("获取编辑数据失败");
                    }
                });
            };
            /**选择合同 --获取需要退款的流水序号 */
            $scope.selectContract = function(index) {
                var arrPayId = $scope.arrPayId;
                var pid = arrPayId.indexOf(index)
                if (pid == -1) {
                    $scope.arrPayId.push(index);
                    $scope.usercontracts[index]['is_refund'] = false;
                } else {
                    $scope.arrPayId.splice(pid, 1);
                    $scope.usercontracts[index]['will_refund'] = 0;
                    $scope.usercontracts[index]['is_refund'] = true;
                }
                $scope.combine();
            };
            /**add输入框触发 */
            $scope.changeRefund = function(index) {
                /**判断是否超过单笔最大额度 */
                var combine = parseInt($scope.usercontracts[index]['will_refund']) + parseInt($scope.usercontracts[index]['refunded']);
                var pay_mount = $scope.usercontracts[index]['pay_mount'];
                if (pay_mount < combine) {
                    alert('单笔流水超过最高退款金额');
                    $scope.usercontracts[index]['will_refund'] = 0;
                }
                $scope.combine('add');
            };

            /**update输入框触发 */
            $scope.changeRefundOfUpDate = function(index) {
                var combine = parseInt($scope.refundArr[index]['refund_mount']) + parseInt($scope.refundArr[index]['pay_refund_mount']);
                var pay_mount = $scope.refundArr[index]['pay_mount'];
                if (pay_mount < combine) {
                    alert('单笔流水超过最高退款金额');
                    $scope.refundArr[index]['refund_mount'] = 0;
                }
                $scope.combine('update');
            };

            /**核算退款总额 */
            $scope.combine = function(type) {
                var mount = 0;
                // var length = $scope.usercontracts.length;
                if (type == 'add') {
                    for (var i in $scope.usercontracts) {
                        mount += parseInt($scope.usercontracts[i]['will_refund']);
                    }
                } else {
                    for (var j in $scope.refundArr) {
                        mount += parseInt($scope.refundArr[j]['refund_mount']);
                    }
                }
                $scope.refund_mount = mount;
            };

            /**展示添加邮寄记录界面 */
            $scope.addDelivery = function() {
                $scope.isAddUser = true;
            };
            /**关闭添加邮寄记录界面 */
            $scope.addDeliveryNo = function() {
                $scope.isAddUser = false;
            };
            /**合并邮寄记录 */
            $scope.saveItem = function() {
                if ($scope.delivery) {
                    $scope.deliveryArr.push($scope.delivery);
                    $scope.isAddUser = false
                };
            };

            /**邮寄的表单验证 */
            $scope.saveItemF = function() {
                if ($('.popup.deliveryF.form').form('is valid')) {
                    $scope.saveItem();
                    $scope.delivery = {};
                    return true;
                }
                return false;
            };

            /**邮寄的表单验证 */
            $scope.saveItemC = function() {
                if ($('.popup.deliveryC.form').form('is valid')) {
                    $scope.saveItem();
                    $scope.delivery = {};
                    return true;
                }
                return false;
            };

            /**界面加载自动运行 */
            $scope.auto = function() {
                $scope.getPageOption();
                $scope.getDataList();
            };
            $scope.auto();

            /**获取所选客户信息 */
            $scope.load_user = function(_name) {
                var deferred = $q.defer();
                if (_name) {
                    $scope.busy = dataFactoryCRM.postDataByAPI('user/searchByName', { 'name': _name })
                        .then(function(d) {
                            deferred.resolve(d);
                        });
                } else
                    deferred.reject('参数提交错误');
                return deferred.promise;
            };

            /**添加退款--客户信息联想 */
            $scope.load_customer = function() {
                if (!$scope.add_data.userphone) {
                    $scope.add_data.contracts = [];
                } else {
                    $scope.busy = dataFactoryCRM.postDataByAPI('refund/customer', { 'userphone': $scope.add_data.userphone })
                        .then(function(d) {
                            if (d && d.rcode == 1) { /*匹配到客户*/
                                $scope.usercontracts = d.contracts;
                            } else {
                                $scope.usercontracts = [];
                            }
                        });
                }
            };

            /*监视搜索条件变化*/
            $scope.$watch('search_param.status', function(newValue, oldValue) {
                if (newValue == oldValue) return true;
                $scope.refundpage.pageNow = 1;
                $scope.search_param.reason = -1;
                $scope.getDataList();
            }, true);

            /* 根据员工姓名自动匹配后台员工 */
            $scope.$watch('edit_data.sales_name', function(newValue, oldValue) {
                if (newValue == oldValue) return true;
                $scope.load_user(newValue).then(function(d) {
                    if (d && 1 == d.rcode) {
                        $scope.edit_data.sales_id = d.data.user_id;
                        $scope.edit_data.sales_sector = d.data.sector_id;
                        $scope.edit_data.sales_name = d.data.nickname;
                    } else if (d && 0 == d.rcode) {
                        $scope.edit_data.sales_name = '';
                        $scope.edit_data.sales_id = null;
                    }
                });
            }, true);

            $scope.$watch('edit_data.manager_name', function(newValue, oldValue) {
                if (newValue == oldValue) return true;
                $scope.load_user(newValue).then(function(d) {
                    if (d && 1 == d.rcode) {
                        $scope.edit_data.sales_manager = d.data.user_id;
                        $scope.edit_data.manager_name = d.data.nickname;
                    } else if (d && 0 == d.rcode)
                        $scope.edit_data.sales_manager = '';
                });
            }, true);

            /* 根据员工姓名自动匹配后台员工 */
            $scope.$watch('add_data.sales_name', function(newValue, oldValue) {
                if (newValue == oldValue) return true;
                $scope.load_user(newValue).then(function(d) {
                    if (d && 1 == d.rcode) {
                        $scope.add_data.sales_id = d.data.user_id;
                        $scope.add_data.sales_sector = d.data.sector_id;
                        $scope.add_data.sales_name = d.data.nickname;
                    } else if (d && 0 == d.rcode) {
                        $scope.add_data.sales_name = '';
                        $scope.add_data.sales_id = null;
                    }
                });
            }, true);

            $scope.$watch('add_data.manager_name', function(newValue, oldValue) {
                if (newValue == oldValue) return true;
                $scope.load_user(newValue).then(function(d) {
                    if (d && 1 == d.rcode) {
                        $scope.add_data.sales_manager = d.data.user_id;
                        $scope.add_data.manager_name = d.data.nickname;
                    } else if (d && 0 == d.rcode)
                        $scope.add_data.sales_manager = '';
                });
            }, true);

            /**自动补全多输入 */
            $scope.customerInputChanged = function($item) {
                $scope.checkCustomer = $item;
            };

            $scope.$watch('checkCustomer', function(newValue, oldValue) {
                if (newValue == oldValue) return true;
                // alert($scope.checkCustomer);
                if (newValue) {
                    $scope.getCustomer(newValue);
                }
                if ((newValue != $scope.add_data.customer_name) && oldValue) {
                    $('#add_data_userphone1').val('');
                    $scope.delivery.recipients = '';
                    $scope.delivery.delivery_phone = '';
                    $scope.usercontracts = [];
                }
            });

        })
        .directive('refundReason', function() {
            return {
                restrict: 'A',
                template: "{{reason}}",
                link: function(scope, element, attrs) {
                    function getName(code) {
                        var reasons = scope.$parent && scope.$parent.pageOption.reasons ? scope.$parent.pageOption.reasons : [];
                        if (reasons) {
                            for (var i = 0; i < reasons.length; i++) {
                                if (reasons[i].id == code)
                                    return reasons[i].name;
                            }
                        }
                        return '';
                    }
                    if (attrs.id) {
                        scope.reason = getName(scope.$eval(attrs.id));
                    }
                }
            };
        })
        .directive('refundStatus', function() {
            return {
                restrict: 'A',
                template: "{{status}}",
                link: function(scope, element, attrs) {
                    if (attrs.status) {
                        // '退款申请状态：0、申请中，未处理；10、取消；20、申请失败；30、风控确认待财务审核；31、财务审核失败，待风控再次确认；40、退款成功(财务确认)',

                        var code = scope.$eval(attrs.status);
                        // var Names = ['待审核', '审核成功', '审核失败', '取消'];
                        var Names = {
                            0: '待处理',
                            10: '已取消',
                            20: '申请失败',
                            30: '风控确认',
                            31: '退款失败',
                            40: '退款成功',
                        };
                        scope.status = Names[code];
                    }
                }
            };
        })
        .directive('signStatus', function() {
            return {
                restrict: 'A',
                template: "{{status}}",
                link: function(scope, element, attrs) {
                    if (attrs.status) {
                        // 0、未处理；1、暂不寄；2、等待寄回 3、签完 4、作废重签 5、拒签',
                        var code = scope.$eval(attrs.status);
                        var Names = ['未处理', '暂不寄', '等待寄回', '签完', '作废重签', '拒签'];
                        scope.status = Names[code];
                    }
                }
            };
        })
        .directive('conState', function() {
            return {
                restrict: 'A',
                template: "{{status}}",
                link: function(scope, element, attrs) {
                    if (attrs.state) {
                        //-1:合同取消；0:待审核;1:进行中； 2、已经终止；3、已完成
                        var code = scope.$eval(attrs.state);
                        code += 1;
                        var Names = ['合同取消', '待审核', '进行中', '已经终止', '已完成'];
                        scope.status = Names[code];
                    }
                }
            };
        })
        .directive('numFormat', function() {
            return {
                scope: {
                    model: '=ngModel'
                },
                link: function(scope, elm, attrs, ctrl) {

                    // function format() {
                    //     if (isNaN(scope.model) || scope.model == "") {
                    //         scope.model = "0.00";
                    //     } else {
                    //         //最多保留两位小数
                    //         var f = parseFloat(scope.model);
                    //         var f = Math.round(scope.model * 100) / 100;
                    //         var s = f.toString();
                    //         var rs = s.indexOf('.');
                    //         if (rs < 0) {
                    //             s = s + ".00";
                    //         } else {
                    //             while (s.length <= rs + 2) { s += '0'; }
                    //         }
                    //         scope.model = s;
                    //     }
                    // }

                    function format() {
                        if (isNaN(scope.model) || scope.model == "") {
                            scope.model = "0";
                        } else {
                            scope.model = parseInt(scope.model);
                        }
                    }

                    format(); //初始化
                    $(elm).bind("blur", format); //jq方式绑定事件
                }
            };
        });

});